/**
 * Copyright 2014  XCL-Charts
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @Project XCL-Charts
 * @Description Android图表基类库
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 * @Copyright Copyright (c) 2014 XCL-Charts (www.xclcharts.com)
 * @license http://www.apache.org/licenses/  Apache v2 License
 * @version 1.0
 */
package com.demo.xclcharts.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import org.xclcharts.chart.AreaChart
import org.xclcharts.chart.AreaData
import org.xclcharts.renderer.XEnum
import org.xclcharts.renderer.info.AnchorDataPoint
import java.text.DecimalFormat
import java.util.LinkedList

/**
 * @ClassName AreaChart01View
 * @Description  面积图例子
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 */
class AreaChart01View : DemoView, Runnable {
    private val TAG = "AreaChart01View"
    private val chart = AreaChart()

    //标签集合
    private val mLabels = LinkedList<String>()

    //数据集合
    private val mDataset = LinkedList<AreaData>()
    private val mPaintTooltips = Paint(Paint.ANTI_ALIAS_FLAG)

    constructor(context: Context?) : super(context) {
        // TODO Auto-generated constructor stub
        initView()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView()
    }

    private fun initView() {
        chartLabels()
        chartDataSet()
        chartRender()
        Thread(this).start()

        //綁定手势滑动事件
        this.bindTouch(this, chart)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //图所占范围大小
        chart.setChartRange(w.toFloat(), h.toFloat())
    }

    private fun chartRender() {
        try {
            //设置绘图区默认缩进px值,留置空间显示Axis,Axistitle....		
            val ltrb = barLnDefaultSpadding
            chart.setPadding(
                ltrb[0].toFloat(),
                ltrb[1].toFloat(),
                ltrb[2].toFloat(),
                ltrb[3].toFloat()
            )

            //轴数据源						
            //标签轴
            chart.setCategories(mLabels)
            //数据轴
            chart.dataSource = mDataset
            chart.crurveLineStyle = XEnum.CrurveLineStyle.BEELINE

            //数据轴最大值
            chart.dataAxis.setAxisMax(100.0)
            //数据轴刻度间隔
            chart.dataAxis.axisSteps = 10.0

            //网格
            chart.plotGrid.showHorizontalLines()
            chart.plotGrid.showVerticalLines()
            //把顶轴和右轴隐藏
            //chart.hideTopAxis();
            //chart.hideRightAxis();
            //把轴线和刻度线给隐藏起来
            chart.dataAxis.hideAxisLine()
            chart.dataAxis.hideTickMarks()
            chart.categoryAxis.hideAxisLine()
            chart.categoryAxis.hideTickMarks()

            /*
				//标题
				chart.setTitle("区域图(Area Chart)");
				chart.addSubtitle("(XCL-Charts Demo)");	
				//轴标题
				chart.getAxisTitle().setLowerAxisTitle("(年份)");
				*/
            //透明度
            chart.setAreaAlpha(200)

            /*
				//显示图例
				chart.getPlotLegend().showLegend();
				
				//激活点击监听
				chart.ActiveListenItemClick();
				//为了让触发更灵敏，可以扩大5px的点击监听范围
				chart.extPointClickRange(5);
				*/
            //定义数据轴标签显示格式
            chart.dataAxis.setLabelFormatter { value -> // TODO Auto-generated method stub		
                val tmp = value.toDouble()
                val df = DecimalFormat("#0")
                val label = df.format(tmp).toString()
                label
            }

            //设定交叉点标签显示格式
            chart.setItemLabelFormatter { value -> // TODO Auto-generated method stub
                val df = DecimalFormat("#0")
                df.format(value).toString()
            }

            //chart.disablePanMode();
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            e.printStackTrace()
            Log.e(TAG, e.toString())
        }
    }

    private fun chartDataSet() {
        //将标签与对应的数据集分别绑定
        //标签对应的数据集
        val dataSeries1: MutableList<Double> = LinkedList()
        dataSeries1.add(0.0) //55
        dataSeries1.add(60.0)
        dataSeries1.add(71.0)
        dataSeries1.add(40.0)
        dataSeries1.add(35.0)
        val dataSeries2: MutableList<Double> = LinkedList()
        dataSeries2.add(10.0)
        dataSeries2.add(22.0)
        dataSeries2.add(30.0)
        dataSeries2.add(30.0) //30 
        dataSeries2.add(0.0) //15
        val dataSeries3: MutableList<Double> = LinkedList()
        dataSeries3.add(35.0)
        dataSeries3.add(45.0)
        dataSeries3.add(65.0)
        dataSeries3.add(75.0)
        dataSeries3.add(55.0)

        //设置每条线各自的显示属性
        //key,数据集,线颜色,区域颜色
        val line1 = AreaData("小熊", dataSeries1, Color.BLUE, Color.YELLOW)
        //不显示点
        line1.dotStyle = XEnum.DotStyle.HIDE
        /*
		line1.setApplayGradient(true);
		line1.setAreaBeginColor(Color.WHITE);
		line1.setAreaEndColor(Color.YELLOW);
		*/
        val line2 = AreaData(
            "小小熊", dataSeries2,
            Color.rgb(79, 200, 100), Color.GREEN
        )
        //设置线上每点对应标签的颜色
        line2.dotLabelPaint.color = Color.RED
        //设置点标签
        line2.labelVisible = true
        line2.labelOptions.setLabelBoxStyle(XEnum.LabelBoxStyle.RECT)
        line2.labelOptions.box.backgroundPaint.color = Color.rgb(250, 194, 142)
        val line3 = AreaData(
            "小小小熊", dataSeries3,
            Color.rgb(246, 134, 31), Color.rgb(213, 198, 126)
        )
        //设置线上每点对应标签的颜色
        //line3.getDotLabelPaint().setColor(Color.YELLOW);
        line3.lineStyle = XEnum.LineStyle.DOT
        mDataset.add(line1)
        mDataset.add(line3)
        mDataset.add(line2)
    }

    private fun chartLabels() {
        mLabels.add("2010")
        mLabels.add("2011")
        mLabels.add("2012")
        mLabels.add("2013")
        mLabels.add("2014")
    }

    override fun render(canvas: Canvas) {
        try {
            chart.render(canvas)
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // TODO Auto-generated method stub		
        super.onTouchEvent(event)
        if (event.action == MotionEvent.ACTION_UP) {
            triggerClick(event.x, event.y)
        }
        return true
    }

    //触发监听
    private fun triggerClick(x: Float, y: Float) {
        val record = chart.getPositionRecord(x, y) ?: return
        val lData = mDataset[record.dataID]
        val lValue = lData.linePoint[record.dataChildID]

        /*
		Toast.makeText(this.getContext(), 
				record.getPointInfo() +
				" Key:"+lData.getLineKey() +
				" Label:"+lData.getLabel() +								
				" Current Value:"+Double.toString(lValue), 
				Toast.LENGTH_SHORT).show();	
		*/
        val r = record.radius
        chart.showFocusPointF(record.position, r + r * 0.5f)
        //chart.getFocusPaint().setStyle(Style.STROKE);
        chart.focusPaint.strokeWidth = 3f
        chart.focusPaint.color = Color.RED
        chart.focusPaint.textAlign = Paint.Align.CENTER


        //在点击处显示tooltip
        mPaintTooltips.color = Color.YELLOW
        chart.toolTip.backgroundPaint.color = Color.GRAY
        //chart.getToolTip().setCurrentXY(x,y);
        chart.toolTip.setCurrentXY(record.position.x, record.position.y)
        chart.toolTip.setStyle(XEnum.DyInfoStyle.CAPRECT)
        chart.toolTip.addToolTip(" Key:" + lData.lineKey, mPaintTooltips)
        chart.toolTip.addToolTip(" Label:" + lData.label, mPaintTooltips)
        chart.toolTip.addToolTip(
            " Current Value:" + java.lang.Double.toString(lValue),
            mPaintTooltips
        )
        chart.toolTip.setAlign(Paint.Align.CENTER)
        this.invalidate()
    }

    override fun run() {
        // TODO Auto-generated method stub
        try {
            chartAnimation()
        } catch (e: Exception) {
            Thread.currentThread().interrupt()
        }
    }

    private fun chartAnimation() {
        try {
            chart.plotLegend.hide()
            val ltrb = barLnDefaultSpadding
            for (i in 8 downTo 1) {
                Thread.sleep(100)
                chart.setPadding(
                    ltrb[0].toFloat(),
                    ltrb[1].toFloat(),
                    (i * ltrb[2]).toFloat(),
                    ltrb[3].toFloat()
                )
                if (1 == i) drawTitle()
                postInvalidate()
            }
        } catch (e: Exception) {
            Thread.currentThread().interrupt()
        }
    }

    private fun drawTitle() {
        //标题
        chart.setTitle("区域图(Area Chart)")
        chart.addSubtitle("(XCL-Charts Demo)")
        //轴标题
        chart.axisTitle.lowerTitle = "(年份)"

        //显示图例
        chart.plotLegend.show()

        //激活点击监听
        chart.ActiveListenItemClick()
        //为了让触发更灵敏，可以扩大5px的点击监听范围
        chart.extPointClickRange(5)
        chart.showClikedFocus()

        //批注
        val mAnchorSet: MutableList<AnchorDataPoint> = ArrayList()
        val an2 = AnchorDataPoint(1, 3, XEnum.AnchorStyle.CIRCLE)
        an2.bgColor = Color.GRAY
        an2.anchorStyle = XEnum.AnchorStyle.CIRCLE
        val an3 = AnchorDataPoint(1, 4, XEnum.AnchorStyle.CIRCLE)
        an3.bgColor = Color.RED
        an3.anchorStyle = XEnum.AnchorStyle.RECT
        an3.areaStyle = XEnum.DataAreaStyle.STROKE

        //从点到底的标识线
        val an4 = AnchorDataPoint(2, 2, XEnum.AnchorStyle.TOBOTTOM)
        an4.bgColor = Color.YELLOW
        an4.lineWidth = 15
        val an5 = AnchorDataPoint(2, 1, XEnum.AnchorStyle.TORIGHT)
        an5.bgColor = Color.WHITE
        an5.lineWidth = 15

        //AnchorDataPoint an6 = new AnchorDataPoint(2,1,XEnum.AnchorStyle.HLINE);
        //an6.setBgColor(Color.WHITE);
        //an6.setLineWidth(15);
        mAnchorSet.add(an2)
        mAnchorSet.add(an3)
        mAnchorSet.add(an4)
        mAnchorSet.add(an5)
        //mAnchorSet.add(an6);
        chart.anchorDataPoint = mAnchorSet
    }
}